/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import {
  Button,
  Classes,
  Dialog,
  FormGroup,
  Intent,
  Position
} from '@blueprintjs/core';
import PasswordMask from 'react-password-mask';
import { FormValidation } from 'calidation';

// Services
import { UserService } from '../../../../../../services';

// Utils
import { Saiku } from '../../../../../../utils';

// Constants
const FORM_VALIDATION_CONFIG = {
  password: {
    isRequired: 'Password field is required',
    isMinLength: {
      message: 'Password must at least be 4 characters long',
      length: 4
    }
  },
  repeatPassword: {
    isRequired: 'Please fill out the password a second time',
    isEqual: ({ fields }) => ({
      message: 'The two password must match',
      value: fields.password,
      validateIf: fields.password.length > 0
    })
  }
};

class ChangePasswordFormDialog extends Component {
  state = {
    loading: false
  };

  handleSubmit = ({ fields, errors, isValid }) => {
    if (isValid) {
      const { userData, onClose } = this.props;
      const { id } = userData;
      const { password } = fields;
      const data = {
        ...userData,
        password
      };

      this.setState({ loading: true });

      UserService.updateUser(id, data)
        .then(res => {
          this.setState({ loading: false });

          if (res.status === 200) {
            Saiku.toasts(Position.TOP_RIGHT).show({
              icon: 'tick',
              intent: Intent.SUCCESS,
              message: 'Password updated'
            });

            onClose();
          } else {
            Saiku.toasts(Position.TOP_RIGHT).show({
              icon: 'error',
              intent: Intent.DANGER,
              message: res.statusText
            });
          }
        })
        .catch(error => {
          Saiku.toasts(Position.TOP_RIGHT).show({
            icon: 'error',
            intent: Intent.DANGER,
            message: 'Something went wrong'
          });
        });
    }
  };

  renderForm() {
    const { onClose } = this.props;
    const { loading } = this.state;

    return (
      <FormValidation
        config={FORM_VALIDATION_CONFIG}
        onSubmit={this.handleSubmit}
        style={{ margin: 0 }}
      >
        {({ fields, errors, submitted }) => (
          <Fragment>
            <div className={Classes.DIALOG_BODY}>
              <FormGroup
                label="Password"
                labelFor="password"
                intent={
                  submitted && errors.password ? Intent.DANGER : Intent.NONE
                }
                helperText={submitted && errors.password ? errors.password : ''}
              >
                <PasswordMask
                  id="password"
                  name="password"
                  inputClassName={classnames('bp3-input', {
                    'bp3-intent-danger': submitted && errors.password
                  })}
                  value={fields.password}
                  autoFocus
                />
              </FormGroup>
              <FormGroup
                label="Repeat Password"
                labelFor="repeatPassword"
                intent={
                  submitted && errors.repeatPassword
                    ? Intent.DANGER
                    : Intent.NONE
                }
                helperText={
                  submitted && errors.repeatPassword
                    ? errors.repeatPassword
                    : ''
                }
              >
                <PasswordMask
                  id="repeatPassword"
                  name="repeatPassword"
                  inputClassName={classnames('bp3-input', {
                    'bp3-intent-danger': submitted && errors.repeatPassword
                  })}
                  value={fields.repeatPassword}
                />
              </FormGroup>
            </div>
            <div className={Classes.DIALOG_FOOTER}>
              <div className={Classes.DIALOG_FOOTER_ACTIONS}>
                <Button
                  type="submit"
                  text="Save"
                  intent={Intent.DANGER}
                  loading={loading}
                />
                <Button text="Close" onClick={onClose} />
              </div>
            </div>
          </Fragment>
        )}
      </FormValidation>
    );
  }

  render() {
    const { userData, onClose } = this.props;
    const { username } = userData;

    return (
      <Dialog
        title={`Change Password for: ${username}`}
        icon="edit"
        canOutsideClickClose={false}
        isOpen={true}
        onClose={onClose}
      >
        {this.renderForm()}
      </Dialog>
    );
  }
}

ChangePasswordFormDialog.propTypes = {
  userData: PropTypes.object.isRequired,
  onClose: PropTypes.func.isRequired
};

export default ChangePasswordFormDialog;
